<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
require('include.php');
use Admin\Controller\Tencentyun\Conf;
use Admin\Controller\Tencentyun\ImageV2;
use Admin\Controller\Tencentyun\Auth;
use Admin\Controller\Tencentyun\ImageProcess;
use Common\Model\NewsVideoModel;
use Common\Model\LiveVideoModel;
use Common\Model\NewsModel;
use Common\Model\LivePanelFilesModel;
use Common\Model\LivePanelImagesModel;
use Think\Cache\Driver\Redis;

class LiveGraphicController extends AdminbaseController{
	private $live;
	private $live_channel;
	private $live_channel_operator;
	private $live_competitor;
	private $live_news_relation;
	private $live_camera_angle;
	private $live_video;
	private $live_resource_video;
	private $news;
	private $admin_user_rcloud_token;
	private $admin_user;
	
	function _initialize() {
		parent::_initialize();
		$this->live = D("Common/Live");
		$this->live_channel = D("Common/LiveChannel");
		$this->live_channel_operator = D("Common/LiveChannelOperator");
		$this->live_competitor = D("Common/LiveCompetitor");
		$this->live_news_relation = D("Common/LiveNewsRelation");
		$this->live_camera_angle = D("Common/LiveCameraAngle");
		$this->live_video = D("Common/LiveVideo");
		$this->live_resource_video = D("Common/LiveResourceVideo");
		$this->news = D("Common/News");
		$this->admin_user_rcloud_token = D("Common/AdminUserRcloudToken");
		$this->admin_user = D("Common/AdminUser");
	}
	

	/**
	 * 创建融云聊天室
	 * @param $live_id
	 * @return mixed
	 */
	private function create_rcloud_chroom($live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'chatroom[room_' . $live_id . ']=n'.$live_id;
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/create.json', $data, $header);
		return $result['code'];
	}
	
	
	/**
	 * 创建融云图文直播聊天室
	 * @param $live_id
	 * @return mixed
	 */
	private function create_rcloud_chroom_pic_txt($live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'chatroom[room_' . $live_id . ']=ptn'.$live_id;
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/create.json', $data, $header);
		return $result['code'];
	}
	

	
	//Tah 20161208
	function live_panel(){
		$live_id = I("get.live_id");
		$add_from = I("get.add_from") ? I("get.add_from") : 0;

		//返回 老版本 1，前端交互0 ，默认0 控制菜单
		$return_val = I("return_val")==0 ? I("return_val") : 1;
		
		
		//获取融云token，供图文直播聊天室使用
		$admin = $this->admin_user_rcloud_token->find($_SESSION["ADMIN_ID"]);
		if(null == $admin || empty($admin)){
			$rcloud_token = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"]);
			$other_rcloud_token1 = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"].'_1');
			$other_rcloud_token2 = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"].'_2');
			//创建token
			$data = array(
					'admin_id'=>$_SESSION["ADMIN_ID"],
					'rcloud_token'=>$rcloud_token,
					'other_rcloud_token1'=>$other_rcloud_token1,
					'other_rcloud_token2'=>$other_rcloud_token2,
			);
			$this->admin_user_rcloud_token->add($data);
		}else{
			$rcloud_token = $admin['rcloud_token'];
			$other_rcloud_token1 = $admin['other_rcloud_token1'];
			$other_rcloud_token2 = $admin['other_rcloud_token2'];
		}

		$this->assign('rcloud_token', $rcloud_token);
		$this->assign('other_rcloud_token1', urlencode($other_rcloud_token1));
		$this->assign('other_rcloud_token2', urlencode($other_rcloud_token2));
		$this->assign('ryAppKey', C('ryAppKey'));
		$this->assign('chatRoomId', "room_$live_id");
		
		
		$list = $this->live->where('live_id = '.$live_id)->find();
		$this->assign("add_from",$add_from);
		$this->assign('live_id', $live_id);
		$this->assign('data', $list);
		$this->assign('return_val',$return_val);
		$this->display();		
	}
	
	
	
	
	//Tah 20161222加入图文直播聊天室
	function live_panel_join_ptchatroom($userId,$live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = "userId=$userId&chatroomId=room_$live_id";
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/join.json', $data, $header);
		return $result['code']==200;
	}
	
	
	//Tah 20161222推送消息到融云
	function live_panel_send_ptmessage($msg_content,$live_id,$fromUserId){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);	
		$data = "content=$msg_content&fromUserId=$fromUserId&toChatroomId=room_$live_id&objectName=RC:TxtMsg";
		
		$result = $this->curl_http(C("ryApiUrl") . '/message/chatroom/publish.json', $data, $header);
		return $result['code']==200;
	}
		
	
// 	//返回live_panel_send_ptmessage函数中的$msg_content部分
// 	function getPushDataForRongYun($data){
// 		/*
// 		$msg_content = array(
// 								"content"	=>"你好,我是图文消息文本！",
// 								"extra"		=>array(
// 														"compere"	=>array(
// 																			"id"	=>"直播员ID",
// 																			"name"	=>"直播员别名",
// 																			"avatar"=>"直播员头像"
// 																			),
// 														"image_url"	=>array("image_url1","image_url2","image_url3"),
// 														"video_url"	=>"",
// 														"user_info"	=>array(
// 																			"user_avatar"	=>"聊天室用户头像",
// 																			"user_username"	=>"聊天室用户姓名",
// 																			"user_id"		=>"聊天室用户ID",
// 																			"user_content"	=>"聊天室用户留言",
// 																			"msg_time"	=>"聊天室用户留言时间,如十二点零六：12:06",
// 																			"msg_date"	=>"聊天室用户留言日期，如2016年12月22日：20161222"
// 																			)														
// 													)
// 							);
// 		*/

// 		$compere = $this->live->getCompere($data['live_id']);
// 		$images = $data['files'];
// 		$user_info = $this->live->getToListUserInfo($data);
// 		$date_time = $this->live->getDateTime($data);
// 		$msg_content = array(
// 								"content"	=>$data['content'],
// 								"extra"		=>array(
// 														"msg_id"=>$data['msg_id'],
// 														"compere"	=>array(
// 																			"id"	=>$compere['creator_id'],//管理员编号
// 																			"name"	=>$compere['live_man_alias'],//"直播员别名",
// 																			"avatar"=>$compere['live_man_avatar_url'],//"直播员头像"
// 																			),
// 														"images_url"	=>$images,   //图片集
// 														"videos_url"	=>$data['videos'],//视频集合
// 														"video_thumbnails"	=>$data['video_thumbnails'],//视频封面图集合
// 														"user_info"	=>$user_info, //上榜用户信息
// 														"date_time" =>$date_time			
// 													)
// 							); 
// 		return json_encode($msg_content);
		
// 	}
// 	//Tah 20161213直播面板的保存按钮的事件
// 	function live_update(){
// 		if (IS_POST) {			
// 			$data = $_POST["data"];
// 			$data=json_decode($data,true);
// 			$live_id = $data['live_id'];
// 			$userId = $_SESSION["ADMIN_ID"];//更新图文消息的管理员
// 			$data['creator_id']  = $userId;			
// 			$data['content'] = strip_tags($data['content']);
// 			$ret = $this->live->Live_Update_Pic_Txt($data,$this->getPushDataForRongYun($data));
// 			if ($data['opt_type']!=2)//<!-- opt_type:1(浏览状态，新增状态）；2（编辑状态）；3：（上榜状态） -->
// 			{			
// 				if ($this->live_panel_join_ptchatroom("ad_$userId",$live_id)){//加入聊天室
// 				  if($data['opt_type'] !='3'){
// 				  	if ($this->live_panel_send_ptmessage($this->getPushDataForRongYun($data),$live_id,$userId)){//发送聊天室消息
// 				  		//更新存储图片信息表
// 				  		$this->save_upload_imgs($data);
// 				  		$ret['msg'] .='，消息成功推送到融云！';
// 				  	}
// 				  	else
// 				  	{$ret['msg'] .='，消息推送融云失败！';}
// 				  }
// 				}
// 				else
// 				{
// 					$ret['msg'] .='，加入图文直播聊天室失败，尚未推送图文消息！';					
// 				}				
// 			}
						
// 			/*
// 			//notifyUrl='www.vradmin.com/index.php?g=api&m=video&a=callback&type=1&is_vr=0&key=b6589fc6ab0dc82cf12099d1c2d40ab994e8410c'
// 			$fileInfo = array('tmp_name'=>'D:\Workspace\phpStudy\WWW\lanxiangjiao.mp4');
// 			$newsModel = new NewsVideoModel();
// 			$fileId    = $newsModel->uploadLivePanelVideo($fileInfo); //上传视频
// 			writelog('filed',$fileId);
// 			*/
// 			echo json_encode($ret);
// 		}		
// 	}



/**
 * 图文直播json数据串
 * @cong.zhao
 */
function getPushDataForRongYun($data){
	$compere = $this->live->getCompere($data['live_id']);
	$images = $data['files'] ? $data['files'] : array();
	$user_info = $this->live->getToListUserInfo($data);
	$date_time = $this->live->getDateTime($data);
	$video_data = array();
	if($data['videos']){
		foreach($data['videos'] as $key=>$value){
			$video_data[$key]['video_url'] = $value;
			$video_data[$key]['video_thumbnail'] = $data['video_thumbnails'][$key];
			$video_data[$key]['video_file_id'] = $data['video_file_ids'][$key];
			$video_data[$key]['video_duration'] = $data['video_durations'][$key];
			$video_data[$key]['video_height'] = $data['video_heights'][$key];
			$video_data[$key]['video_width'] = $data['video_widths'][$key];
			$video_data[$key]['video_size'] = $data['video_sizes'][$key];
		}
	}
	$msg_content = array(
			"msg_id"=>$data['msg_id'],
			"content"	=>$this->userTextEncode($data['content']),
			"compere_id"=>$compere['creator_id'],//管理员编号
			"compere_cate"=>$compere['live_man_cate'],//管理员类别
			"compere_name"	=>$compere['live_man_alias'],//"直播员别名",
			"compere_avatar"=>$compere['live_man_avatar_url'],//"直播员头像"
			"images_url"=>$images,
			"videos_url"=>$data['videos'] ? $data['videos'] : array(),
			"video_thumbnails"=>$data['video_thumbnails'],
			"images_data"=>$images,
			"videos_data"=>$video_data,
			"on_list_user_info"	=>$user_info, //上榜用户信息
			"date_time" =>$date_time
	);
	return json_encode($msg_content);

}

	/**
	 * 把用户输入的文本转义（主要针对特殊符号和emoji表情）
	 * @param $str
	 * @return json
	 */
	public function userTextEncode($str){
		if(!is_string($str))return $str;
		if(!$str || $str=='undefined')return '';
	
		$text = json_encode($str);
		$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
			return addslashes($str[0]);
		},$text);
		return json_decode($text);
	}


/**
 * 图文直播保存消息
 * @cong.zhao
 */
function live_update(){
	if (IS_POST) {
		$data = $_POST["data"];
		$data=json_decode($data,true);
		$live_id = $_POST['live_id'];
		$userId = $_SESSION["ADMIN_ID"];//更新图文消息的管理员
		$data['creator_id']  = $userId;
//		if($userId != 1) {
//			//查看 缓存数据
//			$redis = new Redis();
//			$red_name = C('environment') . '_admin_role_' . $userId;
//			$key = $redis->buildKey($red_name);
//			$red_list = $redis->get_redis($key);
//			if (!$red_list) {
//				//如 无缓存 查看数据
//				$red_list = $this->getAdminRole($userId);
//			} else {
//				$red_list = $red_list[0];
//			}
//
//			$role_arr = array_column($red_list, "action_name");
//			if ($data['opt_type'] == 3) {
//				//上榜
//				if (!in_array("快直播-高级管理-上榜聊天室消息", $role_arr) && !in_array("快直播-图文直播-上榜聊天室消息", $role_arr)) {
//					$ret = array('code'=>'11','msg'=>'暂无此权限','data'=>array());
//					echo json_encode($ret);die;
//				}
//			} else {
//				//消息
//				if (!in_array("快直播-高级管理-添加图文消息", $role_arr) && !in_array("快直播-图文直播-添加图文消息", $role_arr)) {
//					$ret = array('code'=>'11','msg'=>'暂无此权限','data'=>array());
//					echo json_encode($ret);die;
//				}
//			}
//		}
		if($data['onlist_nickname'] && !$data['onlist_user_id']){
			$admin_user_info = $this->admin_user->where(array('username'=>$data['onlist_nickname']))->find();
			if($admin_user_info) $data['onlist_user_id'] = $admin_user_info['admin_id'];
		}
		//$data['content'] = strip_tags($data['content']);
		$ret = $this->live->Live_Update_Pic_Txt($data,$this->getPushDataForRongYun($data));
		if($ret['code'] == '200'){
			$ret['live_id'] = $live_id;
			if($ret['msg'] != "暂无此权限"){
				$redis = new \Redis();
				$redis->connect(C('REDIS_HOST'),C('REDIS_PORT'));
				if(C('REDIS_AUTH')){
					$redis->auth(C('REDIS_AUTH'));
				}
				$redis->set('living_list_'.$live_id,$this->getPushDataForRongYun($data));
			}
		}
		echo json_encode($ret);
	}
}
	

	function sign($array){
		if(!empty($array['sign'])){
			unset($array['sign']);
		}
		ksort($array);
		$string="";
		while (list($key, $val) = each($array)){
			$string .= $key.'='.$val.'&';
		}
		$string = rtrim($string, '&');
		//        echo md5($string);exit();
		return md5($string);
	}
	
	function make_sign_string(){
		$newarray=array();
		$timestamp = time();
		$array['timestamp'] = $timestamp;
		$array['app_key']   = 'helloword';
		$array['unique']    = 'xinhuiwen,fighting!';
		reset($array);
		
		while(list($key,$val) = each($array)){	
			$encode = '';
			$encode = mb_detect_encoding($array[$key], array("ASCII","UTF-8","GB2312","GBK"));
			//iconv($array[$key], "UTF-8", $encode);
			$newarray[$key] = $array[$key];
			
		}
		$sign = $this->sign($newarray); 
		return "timestamp=$timestamp&app_key=".$array['app_key']."&unique=".$array['unique']."&sign=$sign";
	}
	//Tah 20161214
	//http://www.vradmin.com/index.php?g=Admin&m=Live&a=get_live_panel&live_id=1&timestamp=1481705515&app_key=helloword&unique=xinhuiwen%2Cfighting!&sign=baaf9e034864ae896952b589a4ec42ed&token=dc5b4a419b4c23453f9ec166356542e4cd7c9987
	//获取某直播面板的内容列表
	function get_live_panel(){		
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';//图文直播编号
        $msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';//图文直播中的某一消息的编号,如果指定了值，则只返回该消息的内容而非该live_id的全部msg_id的内容
        $file_tag_id = !empty($_REQUEST['file_tag_id']) ? $_REQUEST['file_tag_id'] : '0';//图文直播的某一消息中的文件编号，如果指定了该值，则只返回该文件编号的url地址，而不包含其他的内容
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		$app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
			echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel		
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/get-live-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&msg_id=$msg_id&file_tag_id=$file_tag_id&".$this->make_sign_string()."&token=$token";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));		
	}
	//Tah 20161215
	//删除面板中的图文消息
	function del_live_panel(){
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';
		$msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		 $app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
		echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/del-live-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&".$this->make_sign_string()."&token=$token&msg_id=$msg_id";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));		
	}
	//Tah 20161215
	//置顶图文消息
	function set_top_panel(){
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';
		$msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		 $app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
		echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/set-top-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&".$this->make_sign_string()."&token=$token&msg_id=$msg_id";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));
	}
	
	function set_result(){
		$live_id = I("get.live_id");
		$red_score = I("get.red_score");
		$blue_score = I("get.blue_score");
		$postData = array(
				'red_score'=>$red_score,
				'blue_score'=>$blue_score
		);
		$result = $this->live->where(array('live_id'=>$live_id))->save($postData);
		if($result){
			$this->success("设置成功！", U("Admin/Live/index"));
		}else{
			return $this->error("设置失败！");
		}
	}
	
	function set_status(){
		$live_id = I("get.live_id");
		$status = I("get.status");
		$postData = array(
				'status'=>$status
		);
		$result = $this->live->where(array('live_id'=>$live_id))->save($postData);
		if($result){
			$this->success("设置成功！", U("Admin/Live/index"));
		}else{
			return $this->error("设置失败！");
		}
	}
	
	function get_channel_operators(){
		$channel_id = I("get.channel_id", 0);
		$list = $this->live_channel_operator->getOperatorListByChannelId($channel_id);
		$this->ajaxReturn(array('data'=>$list));
	}
	
	function news_relation(){
		$live_id = I("get.live_id");
		$list = $this->live_news_relation->get_news_relation_list($live_id);
		$data = array();
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				if($value['type'] == 'news'){
					$news = $this->news->where(array('news_id'=>$value['news_id']))->find();
					if($news && !empty($news)){
						$news['relation_id'] = $value['relation_id'];
						$news['type'] = $value['type'];
						$news['weight'] = $value['weight'];
						$data[] = $news;
					}
				}
			}
		}
		$this->assign('live_id', $live_id);
		$this->assign('data', $data);
		$this->display();
	}
	
	function delete_news_relation(){
		$relation_id = I("get.relation_id");
		$session_admin_id = $_SESSION['ADMIN_ID'];
		if($session_admin_id != 1){
			//查看 缓存数据
			$redis = new Redis();
			$red_name = C('environment').'_admin_role_'.$session_admin_id;
			$key = $redis->buildKey($red_name);
			$red_list = $redis->get_redis($key);
			if(!$red_list){
				//如 无缓存 查看数据
				$red_list = $this->getAdminRole($session_admin_id);
			}else{
				$red_list = $red_list[0];
			}

			$role_arr = array_column($red_list,"action_name");

			if(!in_array("快直播-高级管理-删除图文消息", $role_arr) && !in_array("快直播-图文直播-删除图文消息",$role_arr)){
				return $this->error("暂无此权限！");
			}
		}
		$result = $this->live_news_relation->where(array('relation_id' => $relation_id))->delete();
		if($result){
			$this->success("删除成功！", U("Admin/Live/news_relation"));
		}else{
			return $this->error("删除失败！");
		}
	}
	
	function news_relation_add(){
		$live_id = I("post.live_id");
		$news_url = I("post.news_url");
		if(empty($news_url)){
			return $this->error("URL不能为空！");
		}
		$news_weight = I("post.news_weight", 70);
		$a = $this->get_news_id($news_url);
		$data = array(
				'live_id' => $live_id,
				'news_id' => $a['id'],
				'type'    => $a['type'],
				'weight'  => $news_weight
		);
		$result = $this->live_news_relation->add($data);
		if($result){
			$this->success("添加成功！", U("Admin/Live/news_relation", array('live_id'=>$live_id)));
		}else{
			return $this->error("添加失败！");
		}
	}
	
	function edit_news_weight(){
		$relation_id = I("post.relation_id", 0);
		$weight = I("post.weight", 0);
	
		$result = $this->live_news_relation->where(array('relation_id'=>$relation_id))->save(array('weight'=>$weight));
		if($result){
			$this->success("修改成功！", U("Admin/Live/news_relation", array('live_id'=>$live_id)));
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function direct_manage(){
		$live_id = I("get.live_id");
		//查询频道
		$channelList = $this->live_channel->getLiveChannelList();
		$channels = array();
		foreach($channelList as $key=>$value){
			$channels['n_'.$value['channel_id']] = $value['channel_name'];
			$channels['txy_'.$value['channel_id']] = $value['txy_channel_id'];
		}
		//查询视频资源
		$videoList = $this->live_resource_video->get_list($live_id);
		$videos = array();
		foreach($videoList as $key=>$value){
			$videos['n_'.$value['video_id']] = $value['video_name'];
			$videos['f_'.$value['video_id']] = $value['file_id'];
		}
		//查询机位
		$angleList = $this->live_camera_angle->get_camera_angle_list($live_id);
		if(!$angleList || empty($angleList)){
			$angleList = array();
		}else{
			foreach($angleList as $key=>&$value){
				//信号来源 1 频道 2 视频素材 3 外链素材
				if(1 == $value['signal_source']){
					$value['source_name'] = $channels['n_'.$value['source_id']];
					$value['txy_channel_id'] = $channels['txy_'.$value['source_id']];
				}else {
					$value['source_name'] = $videos['n_'.$value['source_id']];
					$value['txy_channel_id'] = 0;
					$value['file_id'] = $videos['f_'.$value['source_id']];
				}
			}
		}
		$angleList[] = array();
		if(!$videoList || empty($videoList)){
			$videoList = array();
		}
		$videoList[] = array('video_id'=>0, 'video_name'=>'','file_name'=>'','category'=>1,'input_file_id'=>'');
		//获取融云token
		$admin = $this->admin_user_rcloud_token->find($_SESSION["ADMIN_ID"]);
		if(null == $admin || empty($admin)){
			$rcloud_token = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"]);
			//创建token
			$data = array(
					'admin_id'=>$_SESSION["ADMIN_ID"],
					'rcloud_token'=>$rcloud_token
			);
			$this->admin_user_rcloud_token->add($data);
		}else{
			$rcloud_token = $admin['rcloud_token'];
		}
		
		
		$this->assign('admin_id', $_SESSION["ADMIN_ID"]);
		$this->assign('rcloud_token', $rcloud_token);
		$this->assign('ryAppKey', C('ryAppKey'));
		$this->assign('angleList', $angleList);
		$this->assign('channelList', json_encode($channelList, JSON_UNESCAPED_UNICODE));
		$this->assign('videoList', $videoList);
		$live = $this->live->find($live_id);
		$this->assign($live);
		$this->display();
	}
	
	private function get_rcloud_token($user_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'userId=' . $user_id . '&name=新汇闻&portraitUri=';
		$result = $this->curl_http(C("ryApiUrl") . '/user/getToken.json', $data, $header);
		return $result['token'];
	}
	
	function edit_angle_name(){
		$camera_id = I("post.camera_id", 0);
		$name = I("post.name", "");
		
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('name'=>$name));
		if($result){
			$this->success("修改成功！");
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function view_live(){
		$signal_source = I("get.signal_source", 1);
		$this->assign("app_id", C('API_AppId'));
		if(1 == $signal_source){
			$channelId = I("get.channel_id", 0);
			$this->assign("channel_id", $channelId);
			$this->display('view_live');
		}else{
			$file_id = I("get.file_id", 0);
			$this->assign("file_id", $file_id);
			$this->display('view_video');
		}
	}
	
	function change_all_status(){
		$live_id = I("post.live_id");
		$status = I("post.status", 1);
		$result = $this->live_camera_angle->where(array('live_id'=>$live_id))->save(array('status'=>$status));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("修改成功！");
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function edit_angle_status(){
		$camera_id = I("post.camera_id", 0);
		$status = I("post.status", 1);
		if(1 == $status){
			//关闭
			$status = 2;
		}else{
			//开启
			$status = 1;
		}
		
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('status'=>$status));
		$this->live->update_live_category($live_id);
		if($result){
			
			$this->success("修改成功！"+$this->live_camera_angle->getLastInsID());
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function add_camera_angle(){
		$live_id = I("post.live_id", 0);
		$name = I("post.name", "");
		$signal_source = I("post.signal_source", 1);
		$source_id = I("post.source_id", 0);
		$operator_id = I("post.operator_id", 0);
		if(empty($operator_id)){
			$operator_id = 0;
		}
		
		$result = $this->live_camera_angle->add(array('live_id'=>$live_id,'signal_source'=>$signal_source,'name'=>$name,'source_id'=>$source_id,'operator_id'=>$operator_id));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("添加成功！");
		}else{
			return $this->error("添加失败！");
		}
	}
	
	function update_camera_angle(){
		$live_id = I("post.live_id", 0);
		$camera_id = I("post.camera_id", 0);
		$name = I("post.name", "");
		$signal_source = I("post.signal_source", 1);
		$source_id = I("post.source_id", 0);
		$operator_id = I("post.operator_id", 0);
		if(empty($operator_id)){
			$operator_id = 0;
		}
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('signal_source'=>$signal_source,'name'=>$name,'source_id'=>$source_id,'operator_id'=>$operator_id));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("修改成功！");
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function angle_list(){
		$live_id = I("get.live_id");
		//查询频道
		$channelList = $this->live_channel->getLiveChannelList();
		$channels = array();
		foreach($channelList as $key=>$value){
			$channels['n_'.$value['channel_id']] = $value['channel_name'];
			$channels['txy_'.$value['channel_id']] = $value['txy_channel_id'];
		}
	    //查询视频资源
		$videoList = $this->live_resource_video->get_list($live_id);
		$videos = array();
		foreach($videoList as $key=>$value){
			$videos['n_'.$value['video_id']] = $value['video_name'];
			$videos['f_'.$value['video_id']] = $value['file_id'];
		}
		//查询机位
		$angleList = $this->live_camera_angle->get_camera_angle_list($live_id);
		if(!$angleList || empty($angleList)){
			$angleList = array();
		}else{
			foreach($angleList as $key=>&$value){
				//信号来源 1 频道 2 视频素材 3 外链素材
				if(1 == $value['signal_source']){
					$value['source_name'] = $channels['n_'.$value['source_id']];
					$value['txy_channel_id'] = $channels['txy_'.$value['source_id']];
				}else {
					$value['source_name'] = $videos['n_'.$value['source_id']];
					$value['txy_channel_id'] = 0;
					$value['file_id'] = $videos['f_'.$value['source_id']];
				}
			}
		}
		$angleList[] = array();
		
		$this->assign('angleList', $angleList);
		$live = $this->live->find($live_id);
		$this->assign($live);
		$this->display();
	}
	
	function changeTimeType($seconds) {
		if ($seconds > 3600) {
			$hours = intval($seconds / 3600);
			$minutes = $seconds % 3600;
			$time = $hours . ":" . gmstrftime('%M:%S', $minutes);
		} else {
			$time = gmstrftime('%H:%M:%S', $seconds);
		}
		return $time;
	}
	
	/**
	 *  后台修改观看人数  数据库  play_count 字段 
	 */
	public function editLiveCount(){
		$type = I('post.type');
		$live_id = I('post.live_id');
		$current_live_count = I('post.val');
// 		$old_live_count = I('post.old_val');

		if($type != 'live' || !$live_id){
			echo $this->ajaxReturn(array('code'=>404, 'msg'=>'修改的直播不存在'), 'JSON');
			exit();
		}
		
		$ret = $this->live->updateLiveCount($live_id, $current_live_count);
		
		if($ret){
			echo $this->ajaxReturn(array('code'=>200, 'msg'=>''), 'JSON');
		}else{
			echo $this->ajaxReturn(array('code'=>400, 'msg'=>'保存失败，请稍后再试！'), 'JSON');
		}
		
		exit();
	}
	
	/*
	 *  后台刷新直播的排序时间  
	 **/
	public function refreshLiveTime(){
		$live_id = I("news_id");
		$data['refresh_time'] = date('Y-m-d H:i:s', time());
		echo $this->live->where(array('live_id'=>$live_id))->save($data);
		exit();
	}
	
	/**
	 *  修改排序
	 */
	
	public function changeWeight(){
		$live_id = I('post.live_id');
		$weight  = I('post.weight');
		
		if(!$live_id || $weight > 255 || $weight < 0){return false;}
		
		$ret = M('vrlive.live')->where(array('live_id'=>$live_id))->save(array('weight'=>$weight));
	
		echo $ret;
		exit();
	}
	
	
	/**
	 * 选择资源池中的视频
	 */
	function chose_video(){
		$live_id = I("get.live_id");
		$chosed_video_ids = I("get.chosed_video_ids");
		//查询视频资源
		$videoList = $this->live_resource_video->get_list($live_id);
		$videos = array();
		foreach($videoList as $key=>$value){
			$videos['n_'.$value['video_id']] = $value['video_name'];
			$videos['f_'.$value['video_id']] = $value['file_id'];
		}
		
		if(!$videoList || empty($videoList)){
			$videoList = array();
		}

		$this->assign('videoList', $videoList);
		$this->assign('chosed_video_ids_arr', explode(',', $chosed_video_ids));
		$this->display();
	}
	
	/**
	 * 上传图片后台操作
	 */
	function upload_img(){
		if($_FILES['imageFile']['name']){
			$newsModel = new NewsModel();  //上传封面图
			$imageUrl = $newsModel->uploadImage();
			echo json_encode($imageUrl);exit;
		}else{
			echo '0';exit;
		}
	}
	
	
	/**
	 * 更新每条信息存储图片信息表
	 */
	function save_upload_imgs($data = array()){
		if($data['live_id'] && $data['msg_id']){
			$save_data = array();
			foreach($data['files'] as $key=>$value){
				$save_data[$key]['live_id'] = $data['live_id'];
				$save_data[$key]['msg_id'] = $data['msg_id'];
				$save_data[$key]['file_url'] = $value;
			}
			$live_panel_images_model = new LivePanelImagesModel();
			if($live_panel_images_model->addAll($save_data)) return true;
		}
		return false;
	}
	
}